#![allow(non_snake_case)]

use std::fmt::Debug;

use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use tauri::State;
use tauri_plugin_system_info::{commands, SysInfoState};
// use tauri_plugin_system_info::model::common::{Process,Network,MacAddr,DiskUsage,Disk,Cpu,Component,Battery};

// 为前端提供简化的系统信息结构
#[derive(Debug, Serialize, Deserialize)]
struct SimplifiedSystemInfo {
    // 系统基本信息
    hostname: String,
    system_name: String,
    os_version: String,
    kernel_version: String,
    
    // 内存信息
    total_memory: u64,
    used_memory: u64,
    memory_usage_percentage: f64,
    
    // CPU信息
    cpu_count: usize,
    cpu_brand: String,
    cpu_usage: f64,
    
    // 磁盘信息
    disks: Vec<SimplifiedDisk>,
    
    // 网络信息
    network_interfaces: Vec<String>,
    total_received: u64,
    total_transmitted: u64,
}

#[derive(Debug, Serialize, Deserialize)]
struct SimplifiedDisk {
    name: String,
    mount_point: String,
    total_space: u64,
    available_space: u64,
    usage_percentage: f64,
    file_system: Option<String>,
}

#[tauri::command]
pub async fn get_detailed_system_info(state: State<'_, SysInfoState>) -> Result<Value, String> {
    // 获取系统信息
    let info = commands::all_sys_info(state)
        .map_err(|e| format!("获取系统信息失败: {}", e))?;
    
    // println!("info: {:?}", info);
    // info.cpus.iter().for_each(|cpu| {
    //     println!("cpu: {:?}", cpu);
    // });
    // info.disks.iter().for_each(|disk| {
    //     println!("disk: {:?}", disk);
    // });
    
    // 直接将整个对象序列化为JSON值
    let sys_info_value = serde_json::to_value(&info)
        .map_err(|e| format!("序列化系统信息失败: {}", e))?;
    
    println!("获取系统信息成功");
    Ok(sys_info_value)
}

#[tauri::command]
pub async fn get_simplified_system_info(state: State<'_, SysInfoState>) -> Result<Value, String> {
    // 获取系统信息
    let info = commands::all_sys_info(state)
        .map_err(|e| format!("获取系统信息失败: {}", e))?;
    
    // 先序列化为JSON，然后处理JSON数据
    let info_json = serde_json::to_value(&info)
        .map_err(|e| format!("序列化系统信息失败: {}", e))?;
    
    // 提取重要信息并简化数据结构
    let simplified_json = extract_important_info_from_json(&info_json);
    
    println!("获取简化系统信息成功");
    Ok(simplified_json)
}

// 从JSON中提取重要数据
fn extract_important_info_from_json(info: &Value) -> Value {
    // 默认值
    let empty_array = json!([]);
    // let empty_object = json!({});
    
    // 基本系统信息
    let hostname = info.get("hostname").and_then(|v| v.as_str()).unwrap_or("Unknown");
    let system_name = info.get("name").and_then(|v| v.as_str()).unwrap_or("Unknown");
    let os_version = info.get("os_version").and_then(|v| v.as_str()).unwrap_or("Unknown");
    let kernel_version = info.get("kernel_version").and_then(|v| v.as_str()).unwrap_or("Unknown");
    
    // 内存信息
    let total_memory = info.get("total_memory").and_then(|v| v.as_u64()).unwrap_or(0);
    let used_memory = info.get("used_memory").and_then(|v| v.as_u64()).unwrap_or(0);
    let memory_usage_percentage = if total_memory > 0 {
        (used_memory as f64 / total_memory as f64) * 100.0
    } else {
        0.0
    };
    
    // CPU信息
    let cpus = info.get("cpus").unwrap_or(&empty_array);
    let cpu_count = info.get("cpu_count").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
    
    let cpu_brand = if cpus.is_array() && !cpus.as_array().unwrap().is_empty() {
        cpus[0].get("brand").and_then(|v| v.as_str()).unwrap_or("Unknown")
    } else {
        "Unknown"
    };
    
    // 计算CPU平均使用率
    let cpu_usage = if cpus.is_array() && !cpus.as_array().unwrap().is_empty() {
        let cpus_array = cpus.as_array().unwrap();
        let total_usage: f64 = cpus_array.iter()
            .filter_map(|cpu| cpu.get("cpu_usage")
            .and_then(|v| v.as_f64()))
            .sum();
        if cpus_array.len() > 0 {
            // CPU使用率通常以0-1表示，但有时可能超过1（如多核心计算总和）
            // 这里确保我们得到0-100范围内的百分比
            let avg_usage = total_usage / cpus_array.len() as f64;
            if avg_usage > 1.0 {
                // 如果使用率是以百分比形式提供的(0-100)，则直接使用
                avg_usage
            } else {
                // 如果使用率是以小数形式提供的(0-1)，则转换为百分比
                avg_usage * 100.0
            }
        } else {
            0.0
        }
    } else {
        0.0
    };
    
    // 处理磁盘信息
    let disks = info.get("disks").unwrap_or(&empty_array);
    let simplified_disks = if disks.is_array() {
        disks.as_array().unwrap().iter().map(|disk| {
            let name = disk.get("name").and_then(|v| v.as_str()).unwrap_or("Unknown");
            let mount_point = disk.get("mount_point").and_then(|v| v.as_str()).unwrap_or("Unknown");
            let total_space = disk.get("total_space").and_then(|v| v.as_u64()).unwrap_or(0);
            let available_space = disk.get("available_space").and_then(|v| v.as_u64()).unwrap_or(0);
            let file_system = disk.get("file_system").and_then(|v| v.as_str()).map(String::from);
            
            let usage_percentage = if total_space > 0 {
                ((total_space - available_space) as f64 / total_space as f64) * 100.0
            } else {
                0.0
            };
            
            json!({
                "name": name,
                "mount_point": mount_point,
                "total_space": total_space,
                "available_space": available_space,
                "usage_percentage": usage_percentage,
                "file_system": file_system
            })
        }).collect::<Vec<_>>()
    } else {
        vec![]
    };
    
    // 网络信息
    let networks = info.get("networks").unwrap_or(&empty_array);
    let (total_received, total_transmitted) = if networks.is_array() {
        networks.as_array().unwrap().iter().fold((0, 0), |acc, network| {
            let received = network.get("total_received").and_then(|v| v.as_u64()).unwrap_or(0);
            let transmitted = network.get("total_transmitted").and_then(|v| v.as_u64()).unwrap_or(0);
            (acc.0 + received, acc.1 + transmitted)
        })
    } else {
        (0, 0)
    };
    
    let network_interfaces = if networks.is_array() {
        networks.as_array().unwrap().iter()
            .filter_map(|net| net.get("interface_name").and_then(|v| v.as_str()).map(String::from))
            .collect::<Vec<_>>()
    } else {
        vec![]
    };

    // 电池相关
    let batteries = info.get("batteries").unwrap_or(&empty_array);
    let battery_info = if batteries.is_array() && !batteries.as_array().unwrap().is_empty() {
        let battery = &batteries.as_array().unwrap()[0];  // 获取第一个电池信息
        
        let vendor = battery.get("vendor").and_then(|v| v.as_str()).unwrap_or("Unknown");
        let model = battery.get("model").and_then(|v| v.as_str()).unwrap_or("Unknown");
        let state = battery.get("state").and_then(|v| v.as_str()).unwrap_or("Unknown");
        let state_of_charge = battery.get("state_of_charge").and_then(|v| v.as_f64()).unwrap_or(0.0);
        let state_of_health = battery.get("state_of_health").and_then(|v| v.as_f64()).unwrap_or(0.0);
        let cycle_count = battery.get("cycle_count").and_then(|v| v.as_u64()).unwrap_or(0);
        let energy = battery.get("energy").and_then(|v| v.as_f64()).unwrap_or(0.0);
        let energy_full = battery.get("energy_full").and_then(|v| v.as_f64()).unwrap_or(0.0);
        let energy_full_design = battery.get("energy_full_design").and_then(|v| v.as_f64()).unwrap_or(0.0);
        
        json!({
            "vendor": vendor,
            "model": model,
            "state": state,
            "percentage": state_of_charge * 100.0, // 转换为百分比
            "health": state_of_health * 100.0,     // 转换为百分比
            "cycle_count": cycle_count,
            "energy": energy,
            "energy_full": energy_full,
            "energy_full_design": energy_full_design,
            "has_battery": true
        })
    } else {
        json!({
            "has_battery": false
        })
    };

    // 创建最终的简化系统信息
    json!({
        "hostname": hostname,
        "system_name": system_name,
        "os_version": os_version,
        "kernel_version": kernel_version,
        "total_memory": total_memory,
        "used_memory": used_memory,
        "memory_usage_percentage": memory_usage_percentage,
        "cpu_count": cpu_count,
        "cpu_brand": cpu_brand,
        "cpu_usage": cpu_usage,
        "disks": simplified_disks,
        "network_interfaces": network_interfaces,
        "total_received": total_received,
        "total_transmitted": total_transmitted,
        "battery": battery_info
    })
}

